﻿namespace OpenPms.Areas.M.Pages.Setup.RoomType;

public class EditModel : PageModel
{
    private readonly Data.AppDbContext db;

    public EditModel(Data.AppDbContext context)
    {
        db = context;
    }

    [BindProperty]
    public TRoomType Item { get; set; } = default!;

    public async Task<IActionResult> OnGetAsync(Guid? id)
    {
        if (id is null)
            Item = new TRoomType { HotelId = User.GetExtId() };
        else
            Item = await db.RoomTypes.FirstAsync(m => m.Id == id && m.HotelId == User.GetExtId());

        return Page();
    }

    // To protect from overposting attacks, enable the specific properties you want to bind to.
    // For more details, see https://aka.ms/RazorPagesCRUD.
    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
        if (Item.IsDelete)
        {
            if (Item.Id != Guid.Empty)
                await db.RoomTypes.Where(ii => ii.Id == Item.Id).ExecuteDeleteAsync();
        }
        else
        {
            if (Item.Id == Guid.Empty)
            {
                var names = Item.Name.Replace("，", ",").Split(',');
                var pinyins = Item.PinYin.Replace("，", ",").Split(",");
                for (int i = 0; i < names.Length; i++)
                    db.RoomTypes.Add(new TRoomType
                    {
                        Id = Guid.NewGuid(),
                        HotelId = User.GetExtId(),
                        Name = names[i],
                        PinYin = pinyins[i]
                    });
            }
            else
                db.Attach(Item).State = EntityState.Modified;
        }
        try
        {
            await db.SaveChangesAsync();
            return RedirectToPage("./Index");

        }
        catch (DbUpdateConcurrencyException)
        {
            db.Entry(Item).Reload();
            ModelState.AddModelError("", Consts.ConcurrencyError);
        }
        catch (DbUpdateException ex)
        {
            ModelState.AddModelError("", "名称重复了？" + ex.Message + ex.InnerException?.Message);
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.Message);
        }
        return Page();
    }
}
